package com.boot.security;

import com.boot.config.IgnoreUrlsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public IJwtAuthenticationTokenFilter myJwtAuthenticationTokenFilter(){
        return new IJwtAuthenticationTokenFilter();
    }

    @Autowired
    private IAuthenticationSuccessHandler authenticationSuccessHandler;

    @Autowired
    private IAuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private ILogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private IlAuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private IAccessDeniedHandler accessDeniedHandler;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
        @SuppressWarnings("SimplifyStreamApiCallChains") String[] ignoreUrls = ignoreUrlsConfig.getUrls().stream().toArray(String[]::new);
        httpSecurity
                .cors()
                .and().csrf().disable()
                .authorizeRequests()
//                .antMatchers(ignoreUrls).permitAll()
//                .antMatchers("/test/**").permitAll()
//                .antMatchers("/mall/**").permitAll()
//                .anyRequest().authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin().successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler)
                .and()
                .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).accessDeniedHandler(accessDeniedHandler)
                .and()
                .logout().logoutSuccessHandler(logoutSuccessHandler)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(myJwtAuthenticationTokenFilter(),UsernamePasswordAuthenticationFilter.class);
        return httpSecurity.build();
    }




}
